package com.emm.yixun.customer.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jws.WebService;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.PriceSchemeDetail;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.SubscribeInfo;
import com.emm.yixun.common.model.TransactionRelation;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.MessageReceiverDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.dto.TransactionRelationDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.RelationTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.customer.service.impl.app.ActivitiProcessServiceImpl;
import com.emm.yixun.customer.service.impl.app.manage.CusAppNoticeManage;

@Service("subscribeServiceFacade")
@WebService(name = "com.emm.yixun.customer.service.SubscribeServiceFacade")
public class SubscribeServiceFacadeImpl implements SubscribeServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private PayDepositService payDepositService;
	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;
	@Autowired
	private UserService userService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private CusAppNoticeManage cusAppNoticeManage;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private TransactionRelationService transactionRelationService;
	@Autowired
	private PayDepositTransactionalService payDepositTransactionalService;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;

	@Override
	public Response<SubscribeDto> save(SubscribeDto dto) {
		Response<SubscribeDto> response = new Response<SubscribeDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			SubscribeDto mDto = subscribeService.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(SubscribeDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = subscribeService.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			SubscribeDto mDto = new SubscribeDto();
			mDto.setId(id);
			int count = subscribeService.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<SubscribeInfo> findByIdInfo(Long id) {
		Response<SubscribeInfo> response = new Response<SubscribeInfo>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Subscribe entity = subscribeService.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				SubscribeInfo info = new SubscribeInfo();
				BeanUtils.copyProperties(entity, info);
				User ur  = new User();
				if(null != info.getCreateUserId()){
					ur = userService.selectById(info.getCreateUserId());
				}
				info.setCreateNameStr("");
				if(null != ur){
					info.setCreateNameStr(ur.getUserName());
				}
				TransactionRelationDto tranDto = new TransactionRelationDto();
				tranDto.setBusinessId(entity.getId());
				tranDto.setDelFlag("0");
				tranDto.setMerchantId(entity.getMerchantId());
				tranDto.setRelationType("5");
				List<TransactionRelation> list = transactionRelationService.selectListByDto(tranDto);
				if (list != null) {
					String str = "";
					for (int i = 0; i < list.size(); i++) {
						TransactionRelation tran = (TransactionRelation) list.get(i);
						User user = userService.selectById(tran.getRelationAgentid());
						if (user != null) {
							str += user.getUserName();
							if ("3".equals(entity.getDealCategory())) {
								str += "(" + tran.getProportionCommission() + "%)，";
							}
						}
					}
					info.setUserName(str);
				}
				response.success(info);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Subscribe> findById(Long id) {
		Response<Subscribe> response = new Response<Subscribe>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Subscribe entity = subscribeService.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Subscribe> findByDto(SubscribeDto dto) {
		ResponseList<Subscribe> response = new ResponseList<Subscribe>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Subscribe> list = subscribeService.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Subscribe> findByDtoJ(SubscribeDto dto) {
		ResponseList<Subscribe> response = new ResponseList<Subscribe>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Subscribe> list = subscribeService.selectListByDtoJ(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<Subscribe> findPageByDto(SubscribeDto dto, Integer begin, Integer row) {
		Page<Subscribe> response = new Page<Subscribe>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Subscribe> page = subscribeService.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Page<SubscribeDto>> getSubscribeList(SubscribeDto reqDto, Integer pageSize, Integer pageNum) {
		Response<Page<SubscribeDto>> resDto = new Response<Page<SubscribeDto>>();
		try {
			reqDto = setQuerySubscribe(reqDto);
			if(reqDto==null){
				resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
				resDto.setSuccess(false);
				return resDto;
			}
			Page<SubscribeDto> payDepositPage = subscribeService.getSubscribeDtoList(reqDto,PageUtil.begin(pageNum, pageSize), pageSize);
			payDepositPage.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(payDepositPage);
			return resDto;
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	
	public SubscribeDto setQuerySubscribe(SubscribeDto reqDto){
		if (StringUtils.isNotBlank(reqDto.getM_auditStatus())) {
			String sql = new String(" and t.audit_status in (");
			String[] audits = reqDto.getM_auditStatus().split(",");
			String sbsql = "";
			for (int i = 0; i < audits.length; i++) {
				sbsql += audits[i];
				if (i != audits.length - 1) {
					sbsql += ",";
				}
			}
			sql += sbsql + ")";
			reqDto.setM_auditStatus(sql);
		}
		
		if (StringUtils.isNotBlank(reqDto.getM_businessStatus())) {
			String sts = reqDto.getM_businessStatus();
			if("9,".equals(sts)) {
				//当业务状态为签约退房时，设置查询查询条件，但不加入少自定义条件中
				reqDto.setIsCkeckOut("1");
				reqDto.setM_businessStatus(" and t.business_status in (5)");
			} else if("8,".equals(sts)) {
				//当业务状态为签约换房时，设置查询查询条件，但不加入少自定义条件中
				reqDto.setIsCkeckOut("2");
				reqDto.setM_businessStatus(" and t.business_status in (5)");
			} else {
				String[] status = sts.split(",");
				String sbsql = "";
				for (int i = 0; i < status.length; i++) {
					sbsql += status[i];
					if (i != status.length - 1) {
						sbsql += ",";
					}
				}
				String sql = new String(" and t.business_status in (");
				sql += sbsql + ") and business_sec_status is null";
				reqDto.setM_businessStatus(sql);
			}
			reqDto.setIscustomerSub(null);
		}
		// 数据权限
		if (SysConstants.openDataPermission) {
			String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(),
			reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
			String[] dataPermissionArr = dataPermission.split(":");
			if ("00".equals(dataPermissionArr[0])) {
					return null;
			}
			reqDto.setDataPermission(dataPermissionArr[1]);
		}
		return reqDto;
	}
	@Override
	public Response<SubscribeDto> addSubscribe(String params, User user,Long oldId) throws Exception{
		/**
		 * 认购 1.保存认筹信息 2.保存家庭成员信息
		 */
		Response<SubscribeDto> response = new Response<SubscribeDto>();
		if (StringUtils.isBlank(params)) {
			response.fail("80000", "参数不能为空！");
			return response;
		}

		SubscribeDto subscribeDto = JSONObject.parseObject(params, SubscribeDto.class);
		subscribeDto.setOldId(oldId);
		if (StringUtils.isNotBlank(subscribeDto.getSubscribeCode())&& null == subscribeDto.getId()) {
			SubscribeDto dto = new SubscribeDto();
			dto.setProjectId(subscribeDto.getProjectId());
			dto.setSubscribeCode(subscribeDto.getSubscribeCode());
			List<Subscribe> subscribe = subscribeService.selectListByDto(dto);
			if (subscribe != null && subscribe.size() != 0) {
				for(Subscribe s : subscribe){
					String auditStatus=s.getAuditStatus();
					//合同编号相同 && 非已退回状态 则认为是合同号码重复
					if(!auditStatus.equals(AuditStatusEnum.REJECT.getNo())){
						logger.error("认购错误", "认购编号重复");
						response.fail("80000", "认购编号重复！");
						return response;
					}
				}
				
			}
		}
		subscribeDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
		subscribeDto.setBusinessStatus("1");
		ProjectRoom projectRoom = projectRoomService.selectById(subscribeDto.getRoomId());
		if (null != projectRoom) {
			subscribeDto.setAccessCode(projectRoom.getProjectCode());
			subscribeDto.setProjectId(projectRoom.getProjectId());
			subscribeDto.setProjectCode(projectRoom.getProjectCode());
		}
        String roomStatus=projectRoom.getRoomStatus();
        if(RoomStatusEnum.BUY.getNo().equals(roomStatus)){
        	response.fail("80000", "该房源已被认购！");
        	return response;
        }else if(RoomStatusEnum.SIGN.getNo().equals(roomStatus)){
        	response.fail("80000", "该房源已被签约！");
        	return response;
        }else if(RoomStatusEnum.RETAIN.getNo().equals(roomStatus)){
        	response.fail("80000", "该房源已被保留！");
        	return response;
        }else if(RoomStatusEnum.MA.getNo().equals(roomStatus)){
        	response.fail("80000", "该房源已被销控！");
        	return response;
        }else if(RoomStatusEnum.SALEL.getNo().equals(roomStatus)){
        	response.fail("80000", "该房源暂不可售");
        	return response;
        }
		if (subscribeDto.getPayDepositId() != null) {
			// 不等于空取(认筹转认购)
			PayDeposit sit = payDepositService.selectById(subscribeDto.getPayDepositId());
			subscribeDto.setFloatingRange(sit.getFloatingRange());
		} else {
			// 直接认筹, 取价格方案
			PriceSchemeDetail detail = priceSchemeDetailService.selectEntityByRoomId(subscribeDto.getRoomId());
			subscribeDto.setFloatingRange(detail.getFloatingRange());
		}
		subscribeDto.setMerchantId(user.getMerchantId());
		subscribeDto.setCreateUserId(user.getId());
		subscribeDto.setUserCode(user.getUserCode());
		subscribeDto.setDelFlag("0");
		subscribeDto.setUpdateUserId(user.getId());
		subscribeDto.setUpdateTime(new Date());
		//移动端用这个字段标示为认购转签约日期
		subscribeDto.setDueTime(subscribeDto.getConversionSignDate());

		SubscribeDto successSubscribeDto = payDepositTransactionalService.addSubscribeWithTransactional(params,
				user, subscribeDto);
		response.success(successSubscribeDto);
		return response;
	}

	/*
	 * 认购延期签约消息
	 */
	@Override
	public CommonResDTO addNotice_YQ(BusinessAbnormaDto businessAbnormaDto, Map<String, Object> managerMap,
			String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			Long roomId=null;
			Long customerId=null;
			String roomName = "";
			String customerName = "";
			String projectCode = "";
			String projectName = "";
			Subscribe subscribe = null;
			if (null != businessAbnormaDto.getBusinessId()) {
				subscribe = subscribeService.selectById(businessAbnormaDto.getBusinessId());
				if (null != subscribe) {
					Project project = projectService.selectById(subscribe.getProjectId());
					if (null != project) {
						projectCode = project.getProjectCode();
						projectName = project.getProjectName();
					}
					ProjectRoom projectRoom = projectRoomService.selectById(subscribe.getRoomId());
					if (null != projectRoom) {
						roomId=projectRoom.getId();
						roomName = projectRoom.getCombinedName();
					} else {
						logger.info("延期签约消息失败,房源不存在! 延期Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("延期签约消息失败,房源不存在!");
						resDto.setResult("0");
						return resDto;
					}
					// 客户名称
					Customer customer = customerService.selectById(subscribe.getCustomerId());
					if (null != customer) {
						customerId=customer.getId();
						customerName = customer.getCustomerName();
					} else {
						logger.info("延期签约消息失败,客户不存在! 延期Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("延期签约消息失败,客户不存在!");
						resDto.setResult("0");
						return resDto;
					}
				}
			} else {
				logger.info("延期签约消息失败,认购信息不存在! 延期Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("延期签约消息失败,认购信息不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 经纪人
			String userName = "";
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(subscribe.getId());
			transactionRelationDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
			List<TransactionRelation> transactionRelationList = transactionRelationService
					.selectListByDto(transactionRelationDto);
			if (transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if (user.getUserName() != null && !"".equals(user.getUserName())) {
						if (transactionRelationList.size() == 1) {
							userName = user.getUserName();
						} else {
							userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
						}
					}
				}
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(
					procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if(e instanceof UserTask){
						List<String> userIds = activitiProcessService.getNodeUserId(subscribe.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
						for(String userId : userIds){
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}
			if (userList.size() == 0) {
				logger.info("延期签约消息失败,待发送客户不存在! 延期签约Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("延期签约消息失败,待发送客户不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 无房认筹, 获取字典表dictionary_value = 'NT16' 的消息模板
			// 消息模板: 延期签约审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
			String msgTemp = "延期签约审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT16");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName)
					.replace("${agent}", userName);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "179");
			noticeParamMap.put("noticeTempType", "NT16");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "延期签约审批申请");
			noticeParamMap.put("merchantId", String.valueOf(businessAbnormaDto.getMerchantId()));
			noticeParamMap.put("projectCode", subscribe.getProjectCode());
			noticeParamMap.put("userCode", businessAbnormaDto.getUserCode());
			noticeParamMap.put("accessCode", businessAbnormaDto.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(businessAbnormaDto.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 * */
			Map<String,String> replaceValuesMap=new HashMap<String,String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, roomId==null?"":String.valueOf(roomId));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId==null?"":String.valueOf(customerId));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,customerName);
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
	    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
	    	/*
			 * (ym) 提醒内容增加超链接 end
			 * */
			NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

			// 推送消息待处理......
			resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "延期签约审批申请");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("延期签约消息异常,延期业务Id = " + businessAbnormaDto.getId(), e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("延期签约消息异常!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	@Override
	public CommonResDTO addNotice_TRG(BusinessAbnormaDto businessAbnormaDto, Map<String, Object> managerMap,
			String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			Long roomId=null;
			Long customerId=null;
			String roomName = "";
			String customerName = "";
			String projectCode = "";
			String projectName = "";
			Subscribe subscribe = null;
			if (null != businessAbnormaDto.getBusinessId()) {
				subscribe = subscribeService.selectById(businessAbnormaDto.getBusinessId());
				if (null != subscribe) {
					Project project = projectService.selectById(subscribe.getProjectId());
					if (null != project) {
						projectCode = project.getProjectCode();
						projectName = project.getProjectName();
					}
					ProjectRoom projectRoom = projectRoomService.selectById(subscribe.getRoomId());
					if (null != projectRoom) {
						roomId=projectRoom.getId();
						roomName = projectRoom.getCombinedName();
					} else {
						logger.info("退认购消息失败,房源不存在! 退认购Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("退认购消息失败,房源不存在!");
						resDto.setResult("0");
						return resDto;
					}
					// 客户名称
					Customer customer = customerService.selectById(subscribe.getCustomerId());
					if (null != customer) {
						customerId=customer.getId();
						customerName = customer.getCustomerName();
					} else {
						logger.info("退认购消息失败,客户不存在! 退认购Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("退认购消息失败,客户不存在!");
						resDto.setResult("0");
						return resDto;
					}
				}
			} else {
				logger.info("退认购消息失败,认购信息不存在! 退认购Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("退认购消息失败,认购信息不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 经纪人
			String userName = "";
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(subscribe.getId());
			transactionRelationDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
			List<TransactionRelation> transactionRelationList = transactionRelationService
					.selectListByDto(transactionRelationDto);
			if (transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if (user.getUserName() != null && !"".equals(user.getUserName())) {
						if (transactionRelationList.size() == 1) {
							userName = user.getUserName();
						} else {
							userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
						}
					}
				}
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(
					procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if(e instanceof UserTask){
						List<String> userIds = activitiProcessService.getNodeUserId(subscribe.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
						for(String userId : userIds){
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}
			if (userList.size() == 0) {
				logger.info("退认购消息失败,待发送客户不存在! 退认购Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("退认购消息失败,待发送客户不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 无房认筹, 获取字典表dictionary_value = 'NT13' 的消息模板
			// 消息模板: 退认购审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
			String msgTemp = "退认购审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT13");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName)
					.replace("${agent}", userName);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "176");
			noticeParamMap.put("noticeTempType", "NT13");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "退认购审批申请");
			noticeParamMap.put("merchantId", String.valueOf(businessAbnormaDto.getMerchantId()));
			noticeParamMap.put("projectCode", subscribe.getProjectCode());
			noticeParamMap.put("userCode", businessAbnormaDto.getUserCode());
			noticeParamMap.put("accessCode", businessAbnormaDto.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(businessAbnormaDto.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 * */
			Map<String,String> replaceValuesMap=new HashMap<String,String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, roomId==null?"":String.valueOf(roomId));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId==null?"":String.valueOf(customerId));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,customerName);
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
	    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
	    	/*
			 * (ym) 提醒内容增加超链接 end
			 * */
			NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

			// 推送消息待处理......
			resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "退认购审批申请");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("退认购消息异常,退认购Id = " + businessAbnormaDto.getId(), e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("退认购消息异常!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	/**
	 * 认购换房提交审批申请 创建并发送提醒消息 subscribeId 认购ID、procInstId 流程实例ID
	 */
	@Override
	public CommonResDTO addSubscribeNotice(Long subscribeId, String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			// 认购
			Subscribe subscribe = subscribeService.selectById(subscribeId);

			// 客户
			String cusName = "";
			Customer customer = customerService.selectById(subscribe.getCustomerId());
			if (customer != null) {
				cusName = customer.getCustomerName();
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(subscribe.getProjectCode());
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(
					procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if(e instanceof UserTask){
						List<String> userIds = activitiProcessService.getNodeUserId(subscribe.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
						for(String userId : userIds){
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}

			// 项目
			String proName = "";
			Project project = null;
			if (subscribe.getProjectId() != null) {
				project = projectService.selectById(subscribe.getProjectId());
				if (project != null) {
					proName = project.getProjectName();
				}
			}

			// 获取经纪人
			String userName = "";
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(subscribe.getId());
			List<TransactionRelation> transactionRelationList = transactionRelationService
					.selectListByDto(transactionRelationDto);
			if (transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if (user.getUserName() != null && !"".equals(user.getUserName())) {
						if (transactionRelationList.size() == 1) {
							userName = user.getUserName();
						} else {
							userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
						}
					}
				}
			}

			// 换房, 获取字典表dictionary_value = 'NT11' 的消息模板
			// 消息模板: 换房：换房审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
			String msgTemp = "换房审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT11");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			// 项目房间
			String roomContent = "";
			ProjectRoom room = projectRoomService.selectById(subscribe.getRoomId());
			if (room != null) {
				roomContent = room.getCombinedName();
			}
			sendMsg = msgTemp.replace("${roomName}", roomContent).replace("${customer}", cusName)
					.replace("${agent}", userName);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "174");
			noticeParamMap.put("noticeTempType", "NT11");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "换房审批申请");
			noticeParamMap.put("merchantId", String.valueOf(subscribe.getMerchantId()));
			noticeParamMap.put("projectCode", subscribe.getProjectCode());
			noticeParamMap.put("userCode", subscribe.getUserCode());
			noticeParamMap.put("accessCode", subscribe.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(subscribe.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 * */
			Map<String,String> replaceValuesMap=new HashMap<String,String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
	    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
	    	/*
			 * (ym) 提醒内容增加超链接 end
			 * */
	    	String action = "换房提交审核提醒";
	    	//String pushType = "SHSQ";
			resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);

			// 推送消息
			if ("1".equals(resDto.getResult())) {
				// 推送消息待处理......
				pushMsg(project.getProjectCode(), proName, "NT11", "换房审批申请");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增换房消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	public void pushMsg(String projectCode, String projectName, String noticeTempType, String actionTitle)
			throws Exception {
		// 1、查询换房审核申请相关推送消息
		// NT11: 换房审核申请
		List<MessageReceiverDto> msgRecList = new ArrayList<MessageReceiverDto>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		// String issueTimeBefore = year + "-" + month + "-" + day + " 00:00:00";
		String issueTimeAfter = year + "-" + month + "-" + day + " 23:59:59";
		MessageReceiverDto withHouseMrDto = new MessageReceiverDto();
		withHouseMrDto.setNoticeTempType(noticeTempType);
		withHouseMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
		// loseCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
		// 推送所有小于 issueTimeAfter 时间的所有消息
		withHouseMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
		List<MessageReceiverDto> withHouseMrList = messageReceiverService.selectPushMsgListByDto(withHouseMrDto);
		if (withHouseMrList != null) {
			for (MessageReceiverDto withHouseMr : withHouseMrList) {
				msgRecList.add(withHouseMr);
			}
		}

		if (msgRecList != null && msgRecList.size() > 0) {
			String noticeIds = "";
			String msgRecIds = "";
			Set<String> noticeIdSet = new HashSet<String>();
			for (MessageReceiverDto msgRecDto : msgRecList) {
				// 开始推送消息
				Map<String, String> pushMap = new HashMap<String, String>();
				pushMap.put("action", "换房提交审核提醒");
				pushMap.put("remindCategoryId", String.valueOf(msgRecDto.getDictionaryId()));
				// pushMap.put("pushType", msgRecDto.getNoticeTempType());
				pushMap.put("pushType", "SHSQ");
				pushMap.put("projectCode", projectCode);
				pushMap.put("projectName", projectName);
				String context = msgRecDto.getContent();
				appPushService.pushMessage(String.valueOf(msgRecDto.getReceiverId()), context, msgRecDto.getTitle(),
						pushMap);

				// 消息ID,Set
				noticeIdSet.add(String.valueOf(msgRecDto.getNoticeId()));
				// 消息接收人ID'S
				if (StringUtils.isNotEmpty(msgRecIds)) {
					msgRecIds += ",";
				}
				msgRecIds += String.valueOf(msgRecDto.getId());
			}
			// 需更新消息ID'S
			if (!noticeIdSet.isEmpty()) {
				for (String noticeId : noticeIdSet) {
					if (StringUtils.isNotEmpty(noticeIds)) {
						noticeIds += ",";
					}
					noticeIds += noticeId;
				}
			}
			// 更新消息
			NoticeDto noticeDto = new NoticeDto();
			noticeDto.setIsSend(IsSendEnum.SEND.getNo());
			noticeService.updates(noticeDto, noticeIds);
			// 更新接收人
			MessageReceiverDto updateMRDto = new MessageReceiverDto();
			updateMRDto.setIsSend(IsSendEnum.SEND.getNo());
			messageReceiverService.updates(updateMRDto, msgRecIds);
		}
	}

	/**
	 * 创建认购消息
	 * 
	 * @param subscribeDto
	 * @return
	 */
	@Override
	public CommonResDTO addNotice_RG(SubscribeDto subscribeDto, String procInstId, String flag) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			// 经纪人
			String userName = "";
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(subscribeDto.getId());
			List<TransactionRelation> transactionRelationList = transactionRelationService
					.selectListByDto(transactionRelationDto);
			if (transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if (user.getUserName() != null && !"".equals(user.getUserName())) {
						if (transactionRelationList.size() == 1) {
							userName = user.getUserName();
						} else {
							userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
						}
					}
				}
			}
            Long roomId=null;
            Long customerId=null;
			String roomName = "";
			String customerName = "";
			String projectCode = "";
			String projectName = "";
			Subscribe subscribe = subscribeService.selectById(subscribeDto.getId());
			if (null != subscribe) {
				Project project = projectService.selectById(subscribe.getProjectId());
				if (null != project) {
					projectCode = project.getProjectCode();
					projectName = project.getProjectName();
				}
				ProjectRoom projectRoom = projectRoomService.selectById(subscribe.getRoomId());
				if (null != projectRoom) {
					roomId=projectRoom.getId();
					roomName = projectRoom.getCombinedName();
					//roomName=WebUtil.addHrefByName(roomName, String.valueOf(subscribe.getRoomId()), "1");
				} else {
					logger.info("认购消息失败,房源不存在! 认购Id = " + subscribeDto.getId());
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("认购消息失败,房源不存在!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}

				// 客户名称
				Customer customer = customerService.selectById(subscribe.getCustomerId());
				if (null != customer) {
					customerName = customer.getCustomerName();
					customerId=customer.getId();
					//customerName=WebUtil.addHrefByName(customerName, String.valueOf(subscribe.getCustomerId()), "2");
				} else {
					logger.info("认购消息失败,客户不存在! 认购Id = " + subscribeDto.getId());
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("认购消息失败,客户不存在!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(
					procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if(e instanceof UserTask){
						List<String> userIds = activitiProcessService.getNodeUserId(subscribe.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
						for(String userId : userIds){
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}
			if (userList.size() == 0) {
				logger.info("认购消息失败,待发送客户不存在! 认购Id = " + subscribeDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("认购消息失败,待发送客户不存在!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}

			// 认购审批申请
			if (flag.equals("1")) {
				// 认购, 获取字典表dictionary_value = 'NT08' 的消息模板
				// 消息模板: 认购审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				String msgTemp = "认购审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
				String sendMsg = "";
				DictionaryDto dicDto = new DictionaryDto();
				dicDto.setDictionaryValue("NT08");
				Dictionary dic = dictionaryService.selectByDto(dicDto);
				if (dic != null) {
					msgTemp = dic.getDictionaryName();
				}
				sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName)
						.replace("${agent}", userName);
				// 创建提醒消息及消息发送人信息
				Map<String, String> noticeParamMap = new HashMap<String, String>();
				noticeParamMap.put("noticeDicId", "171");
				noticeParamMap.put("noticeTempType", "NT08");
				noticeParamMap.put("sendMsg", sendMsg);
				noticeParamMap.put("title", "认购审批申请");
				noticeParamMap.put("merchantId", String.valueOf(subscribeDto.getMerchantId()));
				noticeParamMap.put("projectCode", subscribeDto.getProjectCode());
				noticeParamMap.put("userCode", subscribeDto.getUserCode());
				noticeParamMap.put("accessCode", subscribeDto.getAccessCode());
				noticeParamMap.put("createUserId", String.valueOf(subscribeDto.getCreateUserId()));
				/*
				 * (ym) 提醒内容增加超链接 start
				 * */
				Map<String,String> replaceValuesMap=new HashMap<String,String>();
				replaceValuesMap.put(MsgUtil.ROOM_ID, roomId==null?"":String.valueOf(roomId));
				replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
				replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId==null?"":String.valueOf(customerId));
				replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,customerName);
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
		    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
		    	/*
				 * (ym) 提醒内容增加超链接 end
				 * */
				NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

				// 推送消息待处理......
				resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "认购审批申请");

				// 折扣审批申请
			} else if (flag.equals("2")) {
				// 认购折扣, 获取字典表dictionary_value = 'NT10' 的消息模板
				// 消息模板: 认购折扣审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				String msgTemp = "购房折扣审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
				String sendMsg = "";
				DictionaryDto dicDto = new DictionaryDto();
				dicDto.setDictionaryValue("NT10");
				Dictionary dic = dictionaryService.selectByDto(dicDto);
				if (dic != null) {
					msgTemp = dic.getDictionaryName();
				}
				sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName)
						.replace("${agent}", userName);
				// 创建提醒消息及消息发送人信息
				Map<String, String> noticeParamMap = new HashMap<String, String>();
				noticeParamMap.put("noticeDicId", "173");
				noticeParamMap.put("noticeTempType", "NT10");
				noticeParamMap.put("sendMsg", sendMsg);
				noticeParamMap.put("title", "购房折扣审批申请");
				noticeParamMap.put("merchantId", String.valueOf(subscribeDto.getMerchantId()));
				noticeParamMap.put("projectCode", subscribeDto.getProjectCode());
				noticeParamMap.put("userCode", subscribeDto.getUserCode());
				noticeParamMap.put("accessCode", subscribeDto.getAccessCode());
				noticeParamMap.put("createUserId", String.valueOf(subscribeDto.getCreateUserId()));
				/*
				 * (ym) 提醒内容增加超链接 start
				 * */
				Map<String,String> replaceValuesMap=new HashMap<String,String>();
				replaceValuesMap.put(MsgUtil.ROOM_ID, roomId==null?"":String.valueOf(roomId));
				replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
				replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId==null?"":String.valueOf(customerId));
				replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,customerName);
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
		    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
		    	/*
				 * (ym) 提醒内容增加超链接 end
				 * */
				NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);
				// 推送消息待处理......
				resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "购房折扣审批申请");
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.info("认购消息异常,认购Id = " + subscribeDto.getId(), e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("认购消息异常!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.customer.service.SubscribeServiceFacade#selectSubscribeCustomer(java.lang.Long)
	 */
	@Override
	public Response<SubscribeDto> selectSubscribeCustomer(Long id) {
		Response<SubscribeDto> response = new Response<SubscribeDto>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			SubscribeDto entity = subscribeService.selectSubscribeCustomer(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public void transactionRelationInfo(Long newSubId, Long oldSubId) {
		try {
			TransactionRelationDto relationDto = new TransactionRelationDto();
			relationDto.setBusinessId(oldSubId);
			relationDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
			List<TransactionRelation> transList = transactionRelationService.selectListByDto(relationDto);
			if (transList != null && transList.size() > 0) {
				for (TransactionRelation tran : transList) {
					TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
					BeanUtil.convert2T(transactionRelationDto, tran);
					transactionRelationDto.setBusinessId(newSubId);
					transactionRelationService.create(transactionRelationDto);
				}
			}
		} catch (Exception e) {
			logger.error("transactionRelationInfo error: ", e);
		}
	}

	@Override
	public ResponseList<SubscribeDto> querySubscribeExport(SubscribeDto subscribeDto) {
		ResponseList<SubscribeDto> responseList = new ResponseList<SubscribeDto>();
		try {
			subscribeDto=setQuerySubscribe(subscribeDto);
			subscribeDto.setIsExport("1");
			Page<SubscribeDto> page=subscribeService.getSubscribeDtoList(subscribeDto, 0, 0);
			responseList.setEntity(page.getRows());
			responseList.setSuccess(true);
		} catch (Exception e) {
			logger.error("querySubscribeExport error: ", e);
			responseList.setSuccess(false);
		}
		return responseList;
	}

	/**
	 * 流程页面根据oldid查询认购信息
	 */
	@Override
	public ResponseList<Subscribe> getBusinessDetailByOldId(SubscribeDto dto) {
		ResponseList<Subscribe> response = new ResponseList<Subscribe>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Subscribe> list = subscribeService.getBusinessDetailByOldId(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}


	@Override
	public Response<Integer> getOverdueSignedListCount(SubscribeDto dto) {
		Response<Integer> response=new Response<>();
		try {
			if(null == dto){
				response.setSuccess(false);
				response.setResultMessage("参数不合法");
			}
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}

			int count = subscribeService.getOverdueSignedListCount(dto);
			response.setEntity(count);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setResultMessage("系统异常");
			logger.error("认购转签约逾期提醒记录数错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<SubscribeDto> getOverdueSignedPageModel(SubscribeDto dto, Integer begin, Integer row) {
		Page<SubscribeDto> response= new Page<>();
		try {
			if(null == dto){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
			}
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}

			Page<SubscribeDto> page = subscribeService.getOverdueSignedPageModel(dto, begin, row);
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setErrorMsg("系统异常");
			response.setSuccess(false);
			logger.error("认购转签约逾期提醒分页查询错误：{}",e);
		}
		return response;
	}
}
